from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

from toutiao import Config
from datetime import datetime,timedelta
from auth.auth_jwt import generic_token


def get_user_token(user_id):

    # # 1. 创建序列化器
    # s = Serializer(secret_key=Config.SECRET,expires_in=Config.TOKEN_EXPIRY)
    # # 2. 组织数据
    # data = {
    # "user_id":user_id
    #     }
    # # 3. 生成token
    # return s.dumps(data).decode()


    # 生成两个token
    # 由于token设置短了用户不停的登录不方便,设置长了,
    # 如果被别人获取到token了就不安全,所以设置一个长的一个短的

    # 1.获取当前的时间    utcnow:获取格林尼治时间
    now = datetime.utcnow()

    # 2.分别组织token和refresh_token的payload数据
    token_payload = {"refresh":False,"user_id":user_id}
    refresh_payload = {"refresh":True,"user_id":user_id}

    # 3.分别组织token和refresh_token的过期时间
    token_expiry = now + timedelta(hours=Config.JWT_EXPIRY_HOURS)
    refresh_expiry = now + timedelta(days=Config.JWT_REFRESH_DAYS)

    # 4.生成token
    token = generic_token(token_payload,token_expiry)
    refresh_token = generic_token(refresh_payload,refresh_expiry)

    return token,refresh_token